//
//  TypeViewController.m
//  LiWuShuo
//
//  Created by 袁小航 on 14/11/12.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "TypeViewController.h"
#import "TypeModel.h"
#import "TypeProModel.h"
#import "Type.h"
#import "Define.h"
#import "TypeSubCell.h"
#import "TypeSubCollectionCell.h"
#import <UIImageView+AFNetworking.h>
#import "TypePHCell.h"
#import "TypePHCollectioCell.h"
#import "ShowProViewController.h"
#import "TypeAllTopicModel.h"
#import "TypeAllTopicViewController.h"

@interface TypeViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate>

//定义数组  用来存储分类页面的数据
@property(nonatomic, retain) NSArray *typeTopicArray;
@property(nonatomic, retain) NSArray *typePHArray;
@property(nonatomic, retain) NSArray *typeAllTopicArray;
//创建在V层建立的View
@property(nonatomic, retain) Type *typeView ;

//定义一个在分类页点击row后出现的collectionView
@property(nonatomic, retain) TypeSubCell *subCellCollectionView;

//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//创建headView
@property(nonatomic, strong) UIView *headView;

//三个section Button
@property(nonatomic, strong) UIButton *sectionButton;

//创建一个数组  用来检测section被点击
@property(nonatomic, strong) NSMutableArray *sectionArray;

//创建一个变量，用来判断点击的是哪个sectionButton
@property(nonatomic, assign) NSInteger numOfSection;

//设置这三个button
@property(nonatomic, retain) UILabel *typeName;
@property(nonatomic, retain) UILabel *typeLine;
@property(nonatomic, retain) UIImageView *typeDarkImage;

// 定义一个可变数组  用来删除其他的cell
@property(nonatomic, strong) NSMutableArray *deleteOtherCellArr;

@property(nonatomic, assign) NSInteger tempNum;

// 定义一个装了4个nsnumber的数组
@property(nonatomic, strong) NSMutableArray *allNum;


@end

@implementation TypeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:240/255.0 green:59/255.0 blue:59/255.0 alpha:1];
    self.navigationController.navigationBar.translucent = NO;
    
    UILabel * typeTitle = [[UILabel alloc]init];
    typeTitle.text = @"分类";
    typeTitle.textColor = [UIColor whiteColor];
    typeTitle.font = [UIFont systemFontOfSize:16];
    typeTitle.frame = CGRectMake(0, 0, 40, 30);
    self.navigationItem.titleView = typeTitle;
//    初始化DataSource数据
//    [self initDataSource];
    
//    获取数据
    [self getTypeData];
    
//    创建视图
    [self createTypeView];
    
//    用于判断section是否被点击
    _sectionArray = [[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInteger:0], [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:2], [NSNumber numberWithInt:3], nil];
    
    self.allNum = [[NSMutableArray alloc]initWithObjects:[NSNumber numberWithInteger:0], [NSNumber numberWithInteger:1], [NSNumber numberWithInteger:2], [NSNumber numberWithInt:3], nil];
    
}

#pragma mark - 创建视图
- (void)createTypeView
{
    _typeView = [[Type alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT)];
    _typeView.typeTableView.delegate = self;
    _typeView.typeTableView.dataSource = self;
    
    [self.view addSubview:_typeView];
}

#pragma mark - 获取数据
- (void)getTypeData
{
//    获取“专题”数据
    NSURLSessionDataTask *TopicModel = [TypeModel typeTopicWithBlock:^(NSArray *posts, NSError *error) {
        _typeTopicArray = posts;
        [_typeView.typeTableView reloadData];
    }];
//    获取“对象”和“兴趣”数据
    NSURLSessionDataTask *PHModel = [TypeModel typePHWithBlock:^(NSArray *posts, NSError *error) {
        _typePHArray = posts;
        [_typeView.typeTableView reloadData];
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}
#pragma mark - TableView delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSNumber * num = [NSNumber numberWithInteger:section];
    
    if ([_sectionArray containsObject:num])
    {
        return 0;//一开始是闭合的
    }
    else//展开后
    {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_numOfSection == 1) {
        static NSString *CellIdentifier = @"TypeSubCell";
        TypeSubCell *subCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (subCell == nil) {
            subCell = [[TypeSubCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            subCell.topicCollectionView.delegate = self;
            subCell.topicCollectionView.dataSource = self;
        }
        
        return subCell;
    } else if (_numOfSection == 2) {
        static NSString *PHIdentifier = @"TypePHCell";
        TypePHCell *phCell = [tableView dequeueReusableCellWithIdentifier:PHIdentifier];
        if (phCell == nil) {
            phCell = [[TypePHCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PHIdentifier];
            phCell.PHCollectionView.delegate = self;
            phCell.PHCollectionView.dataSource = self;
        }
        return phCell;
    } else {
        static NSString *PHIdentifier = @"hobbyCell";
        TypePHCell *hobbyCell = [tableView dequeueReusableCellWithIdentifier:PHIdentifier];
        if (hobbyCell == nil) {
            hobbyCell = [[TypePHCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PHIdentifier];
            hobbyCell.PHCollectionView.delegate = self;
            hobbyCell.PHCollectionView.dataSource = self;
        }
        return hobbyCell;
    }
}

#pragma mark - 自定义headerView
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
//    定义一个view  用来添加各个sectionbutton
    self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH, MAIN_SCREEN_HEIGHT)];
    
        NSArray *headNameArr = [NSArray arrayWithObjects:@"『全部专题』", @"♛专题", @"♛对象", @"♛兴趣", nil];
        
        self.sectionButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _sectionButton.frame = CGRectMake(0, 0, MAIN_SCREEN_WIDTH, TYPE_HEIGHT);
        _sectionButton.tag = section + 1000;
        [_sectionButton addTarget:self action:@selector(sectionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_sectionButton setBackgroundImage:[UIImage imageNamed:[NSString stringWithFormat:@"type%d.png", section - 1]] forState:UIControlStateNormal];
        [_headView addSubview:_sectionButton];
    
        //        分类的左侧暗影
        self.typeDarkImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, MAIN_SCREEN_WIDTH / 2, TYPE_HEIGHT)];
        [_typeDarkImage setImage:[UIImage imageNamed:@"featured_trip_cover_mask@2x.png"]];
        [_sectionButton addSubview:_typeDarkImage];
        
        //        分类的名字设置
        self.typeName = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, 120, 40)];
        _typeName.textColor = [UIColor whiteColor];
        _typeName.text = headNameArr[section];
        [_typeName setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
        [_sectionButton addSubview:_typeName];
        
        //        分类的分割线
        self.typeLine = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 320, 2)];
        _typeLine.backgroundColor = [UIColor whiteColor];
        [_sectionButton addSubview:_typeLine];
    return _headView;
}

#pragma mark - head 三个button的响应方法
- (void)sectionButtonAction:(UIButton *)sender
{
    // 如果是第一个section  直接push到下一页 显示全部专题
    if (sender.tag - 1000 == 0) {
        NSURLSessionDataTask *model = [TypeAllTopicModel allTopicWithBlock:^(NSArray *posts, NSError *error) {
            _typeAllTopicArray = posts;
            
            TypeAllTopicViewController *showVC = [[TypeAllTopicViewController alloc]init];
            [self.navigationController pushViewController:showVC animated:YES];
            return;
        }];
    } else {
        // 给numOfSection 赋值
        _numOfSection = sender.tag - 1000;
        
        // num用于标记  检查section是否被点击
        NSNumber *num = [NSNumber numberWithInteger:sender.tag - 1000];
        
        NSMutableArray * indexPathArray = [[NSMutableArray alloc]init];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:sender.tag - 1000];
        [indexPathArray addObject:indexPath];
       
        // 判断是展开还是关闭
        if ([_sectionArray containsObject:num]) {
            // 判断是否已经有section 有插入的row了
            if (_sectionArray.count != _allNum.count) {
                // 如果有
                _deleteOtherCellArr = [NSMutableArray array];
                NSIndexPath *tempIndexPath = [NSIndexPath indexPathForItem:0 inSection:_tempNum];
                [_deleteOtherCellArr addObject:tempIndexPath];
                NSNumber *tempNum = [NSNumber numberWithInteger:_tempNum];
                [_sectionArray removeObject:num];
                [_typeView.typeTableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationTop];
                [_sectionArray addObject:tempNum];
                
                [_typeView.typeTableView deleteRowsAtIndexPaths:_deleteOtherCellArr withRowAnimation:UITableViewRowAnimationAutomatic];
            } else {
                // 如果只是section中没有打开的  走此处  插入row
                [_sectionArray removeObject:num];
                [_typeView.typeTableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationTop];
            }
        } else {
            // 删除点击的section中的row
            [_sectionArray addObject:num];
            [_typeView.typeTableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationTop];
        }
//        将当前点击的section数存入_tempNum
        _tempNum = [num integerValue];
    }
}


#pragma mark - header的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return TYPE_HEIGHT;
}

#pragma mark - row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 240;
}


#pragma mark - UICollectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
//    判断type是哪个  返回响应数组的数组个数
    if (_numOfSection == 1) {
        if (_typeTopicArray.count != 0) {
            return _typeTopicArray.count;
        } else {
            return 4;
        }
    } else if (_numOfSection == 2) {
        if (_typePHArray.count != 0) {
            return [_typePHArray[0] count];
        } else {
            return 4;
        }
    } else if (_numOfSection == 3) {
        if (_typePHArray.count != 0) {
            return [_typePHArray[1] count];
        } else {
            return 4;
        }
    }
    return 0;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_numOfSection == 1) {
        TypeSubCollectionCell *topicCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"topicCell" forIndexPath:indexPath];
        //    设置图片圆角
        topicCell.layer.cornerRadius = 10;
        topicCell.layer.masksToBounds = YES;
        if (_typeTopicArray.count != 0) {
            //    获取“专题”中的图片链接
            NSURL * url = [NSURL URLWithString:[_typeTopicArray[indexPath.row] typeTopicImageUrl]];
            [topicCell.topicImage setImageWithURL:url placeholderImage:[UIImage imageNamed:@"placehold.png"]];
        } else {
            [topicCell.topicImage setImage:[UIImage imageNamed:@"placehold.png"]];
        }
        
        return topicCell;
    } else if (_numOfSection == 2) {
        TypePHCollectioCell *personCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"personCell" forIndexPath:indexPath];
        if (_typePHArray.count != 0) {
            [personCell.phImage setImageWithURL:[NSURL URLWithString:[_typePHArray[0][indexPath.row] icon_url]] placeholderImage:[UIImage imageNamed:@"placehold.png"]];
            personCell.phName.text = [_typePHArray[0][indexPath.row]name];
        } else {
            personCell.phName.text = @"网络异常";
        }
        
        
        return personCell;
    } else if (_numOfSection == 3) {
        TypePHCollectioCell *hobbyCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"hobbyCell" forIndexPath:indexPath];
        if (_typePHArray.count != 0) {
            [hobbyCell.phImage setImageWithURL:[NSURL URLWithString:[_typePHArray[1][indexPath.row] icon_url]] placeholderImage:[UIImage imageNamed:@"placehold.png"]];
            hobbyCell.phName.text = [_typePHArray[1][indexPath.row]name];
        } else {
            hobbyCell.phName.text = @"网络异常";
        }
        
        return hobbyCell;
    }
    return nil;
}

#pragma mark - CollectionView didSelected
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"%ld", (long)indexPath.row);
    if (_numOfSection == 1) {
        ShowProViewController *showVCTopic = [[ShowProViewController alloc]init];
        if (_typeTopicArray.count != 0) {
            showVCTopic.subID = [_typeTopicArray[indexPath.row] sId];
            showVCTopic.subType = @"Topic";
            showVCTopic.subTitle = [_typeTopicArray[indexPath.row] typeTitle];
        }
        [self.navigationController pushViewController:showVCTopic animated:YES];
    } else if (_numOfSection == 2) {
        ShowProViewController *showVCPerson = [[ShowProViewController alloc]init];
        if (_typePHArray.count != 0) {
            showVCPerson.subID = [_typePHArray[0][indexPath.row] sId];
            showVCPerson.subType = @"Person";
            showVCPerson.subTitle = [_typePHArray[0][indexPath.row]name];;
        }
        [self.navigationController pushViewController:showVCPerson animated:YES];
    } else {
        ShowProViewController *showVCHobby = [[ShowProViewController alloc]init];
        if (_typePHArray.count != 0) {
            showVCHobby.subID = [_typePHArray[1][indexPath.row] sId];
            showVCHobby.subType = @"Hobby";
            showVCHobby.subTitle = [_typePHArray[1][indexPath.row]name];
        }
        [self.navigationController pushViewController:showVCHobby animated:YES];
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
